%Basin_Hopping算法

%初始化参数
N = 19;
d = 0.88;
r_min = 1.1;
r_max = 2.3;

%设置初始构型
%fname = sprintf('N=%d.txt',N-1);
fname = sprintf('N=%d.txt',13);
DATA = load(['.\SA_multiple\',fname]);
config_13 = cell(1,N);
for i=1:13
    config_13{i} = DATA(i+14,:);
end
config0 = create_config_multiple(config_13, r_max, r_min);

%极小值演化构型的集合个数为NUM
NUM = 100;
MIN_SET = cell(1,NUM);

STEP = 10000;
T = 1;
dr = 1;
choice = 1;
r_max = 3; r_min = d;

for i=1:NUM
    config_former = config0;
    en_former = en_cal(config0);
    
    %记录退火过程中目前最小能量对应的构型{1}和能量{2}
    en_min = cell(1,2);
    en_min{1} = config_former;
    en_min{2} = en_former;
    
    for j=1:STEP
        config = change_config_multiple(config_former,dr, r_max, r_min, choice);
        en = en_cal(config);
        if(en < en_former)
            config_former = config;
            en_former = en;
            if(en < en_min{2})
                en_min{1} = config;
                en_min{2} = en;
            end
        else
            rand_num = rand;
            factor = exp((en_former-en)/T);
            if(rand_num < factor)
                config_former = config;
                en_former = en;
            else

            end
        end
    end
    
    MIN_SET{i} = en_min;
end

T_max = 1;
T_min = 1e-3;
lambda = 0.9;
step = 1000;
choice = 1;
r_max = 3; r_min = d;

for i=1:NUM
    dr = 0.8;
    T = T_max;
    config_former = MIN_SET{i}{1};
    en_former = MIN_SET{i}{2};
    while T > T_min
        for j = 1:step
            config = change_config_multiple(config_former,dr, r_max, r_min, choice);
            en = en_cal(config);
            if(en < en_former)
                config_former = config;
                en_former = en;
                if(en < en_min{2})
                    en_min{1} = config;
                    en_min{2} = en;
                end
            else
                rand_num = rand;
                factor = exp((en_former-en)/T);
                if(rand_num < factor)
                    config_former = config;
                    en_former = en;
                else

                end
            end
        end
        T = lambda * T;
        dr = lambda^(2/5) * dr;

    end
end

%挑选能量最小构型
EN_MIN = cell(1,2);
EN_MIN = MIN_SET{1};
for k=2:NUM
    if(MIN_SET{k}{2} < EN_MIN{2})
        EN_MIN = MIN_SET{k};
    end
end

%写.txt文件，存数据
fname = sprintf('N=%d.txt',N);
fid = fopen(['.\SA_multiple\',fname],'w');
for k = 1:N
    for m = 1:3
        fprintf(fid, '%.8f\t', EN_MIN{1}{k}(m));
    end
    fprintf(fid, '\n');
end
for m = 1:3
    fprintf(fid, '%.8f\t', EN_MIN{2});
end
fclose(fid);

